<?php


namespace App\Remote\Feishu\Departments;


use Closure;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
use Illuminate\Support\Facades\Log;

class Remote extends \App\Remote\Remote
{

    /**
     * @inheritDoc
     */
    static function getBaseUri(): string
    {
        // TODO: Implement getBaseUri() method.
        return "https://open.feishu.cn";
    }

    public static function registerResponseHandle(): Closure
    {
        return function (string $data) {
            return json_decode($data, JSON_UNESCAPED_UNICODE)["data"];
        };
    }

    /**
     * @return HandlerStack
     */
    public static function getHandlerStack(): HandlerStack
    {
        //获取基础中间件
        $handleStack = parent::getHandlerStack();
        //增加重试中间件
        $handleStack->before("logMiddleware",
            Middleware::retry(function (
                int $retryTimes,
                Request $request,
                Response $response = null,
                \Exception $exception = null
            ) {
                if ($exception) {
                    Log::channel("remoteRequest")->warning("请求重试");
                    return true;
                }
                return false;
            }, function () {
                return 1000 * 5;
            }), "retryMiddleware");

        return $handleStack;
    }
}
